package com.chixing.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Elasticsearch 客户端配置类
 */
@Configuration
public class ElasticsearchConfig {

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        // 1️⃣ 创建 RestClient（连接本地 ES）
        RestClient restClient = RestClient.builder(
                new HttpHost("localhost", 9200)
        ).build();

        // 2️⃣ 创建支持 LocalDateTime 的 ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());

        // 3️⃣ 将 ObjectMapper 注入到 JacksonJsonpMapper 中
        JacksonJsonpMapper jsonpMapper = new JacksonJsonpMapper(objectMapper);

        // 4️⃣ 使用 RestClient 和 Mapper 构造 Transport
        RestClientTransport transport = new RestClientTransport(restClient, jsonpMapper);

        // 5️⃣ 返回 ElasticsearchClient Bean
        return new ElasticsearchClient(transport);
    }
}
